﻿using System.Data.Entity;
using NQueries.Utils;

namespace NQueries
{
    /// <summary>
    /// Defines various extension methods for IDbSet.
    /// </summary>
    public static class DbSetExtensions
    {
        /// <summary>
        /// Gets an entity by its id.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="set"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static TEntity GetById<TEntity>(this IDbSet<TEntity> set, object id) where TEntity : class
        {
            Check.IsNotNull(set, "set");

            TEntity entity = set.Find(id);
            if (entity == null)
                throw new NQueriesException("object of type <{0}> with id <{1}> not found".FormatWith(typeof(TEntity), id));
            return entity;
        }

        /// <summary>
        /// Attaches the entity to the current db context and marks it as modified.
        /// </summary>
        /// <param name="set"></param>
        /// <param name="entity"></param>
        /// <typeparam name="TEntity"></typeparam>
        /// <exception cref="NQueriesException"></exception>
        public static void Update<TEntity>(this IDbSet<TEntity> set, TEntity entity) where TEntity : class
        {
            Check.IsNotNull(set, "set");
            Check.IsNotNull(entity, "entity");

            UnitOfWork.CurrentDataContext.Update(entity);
        }
    }
}